package com.zndroid.upgrader.displayer;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.zndroid.upgrader.R;
import com.zndroid.upgrader.downloader.IDownloadManager;
import com.zndroid.upgrader.downloader.InnerDownloadManager;
import com.zndroid.upgrader.config.UpdateConfiguration;
import com.zndroid.upgrader.db.DBTaskImpl;
import com.zndroid.upgrader.listener.IUpgradeStatusListener;
import com.zndroid.upgrader.listener.IDownloadListener;
import com.zndroid.upgrader.UpgraderX;
import com.zndroid.upgrader.service.DownloadService;
import com.zndroid.upgrader.utils.ApkUtil;
import com.zndroid.upgrader.utils.Constant;
import com.zndroid.upgrader.utils.ScreenUtil;
import com.zndroid.upgrader.widget.NumberProgressBar;

import java.io.File;

/**
 * 内置升级对话框
 */
public class UpdateDialog extends Dialog implements View.OnClickListener, IDownloadListener, IUpgradeStatusListener {

    private Context context;
    private UpgraderX manager;
    private boolean forcedUpgrade;
    private Button update;
    private NumberProgressBar progressBar;
    private ScrollView descriptionScrollView;
    private IUpgradeStatusListener buttonClickListener;
    private int dialogImage, dialogButtonTextColor, dialogButtonColor, dialogProgressBarColor;
    private File apk;

    public UpdateDialog(@NonNull Context context) {
        super(context, R.style.UpdateDialog);
        init(context);

        if (context instanceof Activity) {
            setOwnerActivity((Activity) context);
        }
    }

    /**
     * 初始化布局
     */
    private void init(Context context) {
        this.context = context;
        manager = UpgraderX.getInstance();

        UpdateConfiguration configuration = manager.getConfiguration();
        configuration.setOnDownloadListener(this);

        forcedUpgrade = configuration.isForcedUpgrade();
        setCancelable(!forcedUpgrade);

        //内部按钮点击监听
        buttonClickListener = this;

        IDownloadManager downloadManager = configuration.getHttpManager();
        //使用自己的下载
        if (downloadManager == null) {
            DBTaskImpl task = new DBTaskImpl(context);
            downloadManager = new InnerDownloadManager(manager.getDownloadPath(), task);
            configuration.setHttpManager(downloadManager);
        }

        dialogImage = configuration.getDialogImage();
        dialogButtonTextColor = configuration.getDialogButtonTextColor();
        dialogButtonColor = configuration.getDialogButtonColor();
        dialogProgressBarColor = configuration.getDialogProgressBarColor();

        View view = LayoutInflater.from(context).inflate(R.layout.upx_default_dialog_update, null);
        setContentView(view);
        setWindowSize(context);
        initView(view);
    }

    private void initView(View view) {
        View ibClose = view.findViewById(R.id.ib_close);
        ImageView ivBg = view.findViewById(R.id.iv_bg);
        TextView title = view.findViewById(R.id.tv_title);
        TextView size = view.findViewById(R.id.tv_size);
        TextView description = view.findViewById(R.id.tv_description);

        descriptionScrollView = view.findViewById(R.id.sv_description);
        progressBar = view.findViewById(R.id.np_bar);
        update = view.findViewById(R.id.btn_update);

        update.setTag(IUpgradeStatusListener.UPDATE);

        View line = view.findViewById(R.id.line);
        update.setOnClickListener(this);
        ibClose.setOnClickListener(this);

        //自定义
        if (dialogImage != -1) {
            ivBg.setBackgroundResource(dialogImage);
        }
        if (dialogButtonTextColor != -1) {
            update.setTextColor(dialogButtonTextColor);
        }
        if (dialogButtonColor != -1) {
            StateListDrawable drawable = new StateListDrawable();
            GradientDrawable colorDrawable = new GradientDrawable();
            colorDrawable.setColor(dialogButtonColor);
            colorDrawable.setCornerRadius(ScreenUtil.dip2px(context, 3));
            drawable.addState(new int[]{android.R.attr.state_pressed}, colorDrawable);
            drawable.addState(new int[]{}, colorDrawable);
            update.setBackground(drawable);
        }
        if (dialogProgressBarColor != -1) {
            progressBar.setReachedBarColor(dialogProgressBarColor);
            progressBar.setProgressTextColor(dialogProgressBarColor);
        }
        //强制升级
        if (forcedUpgrade) {
            line.setVisibility(View.GONE);
            ibClose.setVisibility(View.GONE);
            setOnKeyListener(new OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    //屏蔽返回键
                    return keyCode == KeyEvent.KEYCODE_BACK;
                }
            });
        }
        //设置界面数据
        if (!TextUtils.isEmpty(manager.getApkVersionName())) {
            String newVersion = context.getResources().getString(R.string.dialog_new);
            title.setText(String.format(newVersion, manager.getApkVersionName()));
        }
        if (!TextUtils.isEmpty(manager.getApkSize())) {
            String newVersionSize = context.getResources().getString(R.string.dialog_new_size);
            size.setText(String.format(newVersionSize, manager.getApkSize()));
            size.setVisibility(View.VISIBLE);
        }
        description.setText(manager.getApkDescription());
    }

    private void setWindowSize(Context context) {
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenUtil.getWith(context) * 0.8f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ib_close) {
            if (buttonClickListener != null) {
                update.setTag(IUpgradeStatusListener.CANCEL);
                buttonClickListener.onButtonClick(IUpgradeStatusListener.CANCEL);
            }
        } else if (id == R.id.btn_update) {
            int tag = (int) update.getTag();
            switch (tag) {
                case IUpgradeStatusListener.UPDATE:
                    if (buttonClickListener != null) {
                        buttonClickListener.onButtonClick(UPDATE);
                    }
                    break;
                case IUpgradeStatusListener.PAUSE:
                    if (buttonClickListener != null) {
                        buttonClickListener.onButtonClick(PAUSE);
                    }
                    break;
                case IUpgradeStatusListener.CONTINUE:
                    if (buttonClickListener != null) {
                        buttonClickListener.onButtonClick(CONTINUE);
                    }
                    break;
                case IUpgradeStatusListener.INSTALL:
                    if (buttonClickListener != null) {
                        buttonClickListener.onButtonClick(INSTALL);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 强制更新，点击进行安装
     */
    private void installApk() {
        ApkUtil.installApk(context, Constant.AUTHORITIES, apk);
    }

    @Override
    public void start() {
        Log.i("UpGrader", "download start.....");
    }

    @Override
    public void downloading(long max, long progress) {
        if (max != -1 && progressBar.getVisibility() == View.VISIBLE) {
            final int curr = (int) (progress / (double) max * 100.0);
            if (null != getOwnerActivity()) {
                getOwnerActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(curr);
                    }
                });
            }
        } else {
            progressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void done(File apk) {
        this.apk = apk;

        if (manager.getConfiguration().isJumpInstallPage()) {
            installApk();
        } else {
            update.setTag(IUpgradeStatusListener.INSTALL);
            update.setText(R.string.click_hint);
        }
    }

    @Override
    public void error(Exception e) {
        e.printStackTrace();
    }

    @Override
    public void onButtonClick(int id) {
        if (null != manager) {
            //同时抛出按钮点击事件
            if (null != manager.getConfiguration() && (null != manager.getConfiguration().getIUpgradeStatusListener())) {
                manager.getConfiguration().getIUpgradeStatusListener().onButtonClick(id);
            }
        }

        switch ((int)update.getTag()) {
            case IUpgradeStatusListener.UPDATE:
                if (manager.getConfiguration().isOnlyDialogTip()) {//dialog只作为显示更新提示用，仍然使用后台更新
                    dismiss();
                    context.startService(new Intent(context, DownloadService.class));
                } else {
                    manager.getConfiguration().getHttpManager().startDownload(manager.getApkUrl(), manager.getApkName(), this);
                    update.setText(R.string.pause);
                    update.setTag(IUpgradeStatusListener.PAUSE);//点击更新 下一步 - 暂停
                    descriptionScrollView.setVisibility(View.GONE);
                    progressBar.setVisibility(View.VISIBLE);
                }
                break;
            case IUpgradeStatusListener.CONTINUE:
                manager.getConfiguration().getHttpManager().continues();
                update.setText(R.string.pause);
                update.setTag(IUpgradeStatusListener.PAUSE);//点击继续 下一步 - 暂停（直到更新完毕）
                break;
            case IUpgradeStatusListener.PAUSE:
                manager.getConfiguration().getHttpManager().pause();
                update.setText(R.string.continues);
                update.setTag(IUpgradeStatusListener.CONTINUE);//点击暂停 下一步 - 继续（直到更新完毕）
                break;
            case IUpgradeStatusListener.CANCEL:
                dismiss();
                break;
            case IUpgradeStatusListener.INSTALL:
                dismiss();
                installApk();
                break;
        }
    }
}
